package com.cw.jeeyt.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.List;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class PdfGenerator {
    /**
     * @param htmlStr
     * @param out
     * @throws Exception
     * @职责 pdf生成工具
     * @author chenwei;
     * @version v1.0 chenwei 2014-9-17 创建方法
     * @since 2014-9-17 下午1:40:08
     */
    public static void generate(String htmlStr, OutputStream out) throws Exception {
        /*
         * DocumentBuilder builder = DocumentBuilderFactory.newInstance()
         * .newDocumentBuilder(); ByteArrayInputStream bstr = new
         * ByteArrayInputStream(htmlStr .getBytes()); Document doc =
         * builder.parse(bstr); ITextRenderer renderer = new ITextRenderer();
         *
         * ITextFontResolver fontResolver = renderer.getFontResolver();
         * fontResolver.addFont("C:/Windows/Fonts/arialuni.ttf",
         * BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
         * renderer.setDocument(doc, null); renderer.layout();
         * renderer.createPDF(out); out.close();
         */

        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("c:/windows/Fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        System.out.println(htmlStr);
        //renderer.getSharedContext().setBaseURL("file:/" + path + "/images");设置图片路径
        renderer.setDocumentFromString(htmlStr);
        renderer.layout();
        renderer.createPDF(out);
        out.close();
    }

    /**
     * @职责 [将多个PDF文件合并成一个PDF文件]
     * @author chenwei;
     * @version v1.0 chenwei 2014-9-4 创建方法
     * @since 2014-9-4 下午3:18:45
     */
    public static boolean mergePDF(List<String> files, String saveFile) {
        boolean returnValue = false;
        Document document = null;
        PdfReader reader = null;
        PdfReader firstPdfReader = null;
        try {
            firstPdfReader = new PdfReader(files.get(0));
            document = new Document(firstPdfReader.getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(saveFile));
            document.open();
            for (String file : files) {
                try {
                    reader = new PdfReader(file);
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    firstPdfReader.close();
                    reader.close();
                }
            }
            returnValue = true;
        } catch (Exception e) {
            System.out.println("合并PDF文件失败，详细：" + e.getMessage());
        } finally {
            reader.close();
            document.close();
        }
        return returnValue;
    }

    /**
     * @param files
     * @职责 [将pdf文件合并后删除掉多余的pdf文件]
     * @author chenwei;
     * @version v1.0 chenwei 2014-9-5 创建方法
     * @since 2014-9-5 下午2:03:38
     */
    public static void deletePdfFile(List<String> files) {
        if (files != null && files.size() > 0) {
            for (String file : files) {
                File pdfFile = new File(file);
                if (pdfFile.exists()) {
                    try {
                        pdfFile.delete();
                    } catch (Exception e) {
                        //System.out.println("删除文件" + file + "失败");
                        //		+ e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * Word文档转换成PDF文件
     *
     * @param inputFile 要转换的doc文件
     * @param outputFile 要输出的目标文件
     * fileType 目标文件类型�? Doc 1 Dot 2-5 Txt 6 Rtf 7 Txt 8�?0 htm 11
     * Xml 12�?6 Docx 13 Docm 14 Dotx 15 Dotm 17 Pdf
     */

    public static void WordToObject(String inputFile, String outputFile, int fileType) {
        ActiveXComponent wordOpen = new ActiveXComponent("Word.Application"); // 指定类型
        Dispatch dispatch = null;
        boolean flag = false;
        try {
            wordOpen.setProperty("Visible", new Variant(false)); // 设置word不可�?
            dispatch = wordOpen.getProperty("Documents")
                .toDispatch(); // 打开word文件
            Dispatch doc2 = Dispatch.invoke(dispatch, "Open", Dispatch.Method,
                new Object[] {inputFile, new Variant(false), new Variant(true)}, new int[1])
                .toDispatch(); // 作为txt格式保存到临时文�?
            // 如果要生成的目标文件已经存在，则删除
            File tofile = new File(outputFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.invoke(doc2, "SaveAs", Dispatch.Method, new Object[] {outputFile, new Variant(fileType)},
                new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(doc2, "Close", f);// 关闭word
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转换失败，详细：" + e.getMessage());
        } finally {
            wordOpen.invoke("Quit", new Variant[] {});
        }
        if (flag == true) {
            System.out.println("Word转PDF成功");
        } else {
            System.out.println("Word转PDF失败");
        }

    }

    /**
     * @param imagePath
     * @param outputFile
     * @职责 [将图片转换成pdf文件]
     * @author chenwei;
     * @version v1.0 chenwei 2014-9-17 创建方法
     * @since 2014-9-17 下午2:00:06
     */
    public static void ImageToPdf(String imagePath, String outputFile) {
        try {
            // 定义PDF文件大小和边�?
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);
            // 生成PDF文件的路径
            //PdfWriter writer = PdfWriter.getInstance(document,
            //		new FileOutputStream(outputFile));
            // writer.setViewerPreferences(PdfWriter.PageModeFullScreen);
            document.open();
            // 添加图片
            document.add(getImageFile(imagePath));
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("将图片生成pdf失败");
        }

    }

    /**
     * 获得PDF文件所需图片
     *
     * @param imagePath //图片文件路径
     * @return
     * @throws BadElementException
     * @throws MalformedURLException
     * @throws IOException
     */
    public static Image getImageFile(String imagePath) throws BadElementException, MalformedURLException, IOException {
        Image image = Image.getInstance(imagePath);
        float heigth = image.getHeight();
        float width = image.getWidth();
        int percent = getPercent2(heigth, width);
        // 设置图片居中
        image.setAlignment(Image.MIDDLE);
        image.scalePercent(percent + 3);// 表示是原来图像的比例;
        return image;
    }

    /**
     * @param h
     * @param w
     * @return
     * @职责 [调整图片大小]
     * @author chenwei;
     * @version v1.0 chenwei 2014-9-17 创建方法
     * @since 2014-9-17 下午2:52:46
     */
    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

}
